package com.jamie.jvm.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量demo
 * @author jamie
 * @date 2021/3/9 23:17
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        // 模拟3个停车位
        Semaphore semaphore = new Semaphore(3);
        // 模拟6部汽车
        for(int i = 1; i <= 6; i++){
            new Thread(() -> {
                try{
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t 抢到车位");
                    // 暂停一下资源
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + "\t 停车3秒后离开车位");
                }catch(InterruptedException e){
                    e.printStackTrace();
                }finally{
                    // 释放停车位
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "\t 车位空了");
                }
            }, "Thread-" + i).start();
        }
    }

}
